/*
Copyright (c) 2011 Sanjay Dasgupta (sanjay.dasgupta@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package asg;

import java.awt.Color;
import java.awt.Font;
import java.awt.TextArea;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

public class SbazConnector extends TextArea {

    boolean hasError(String s) {
        String exceptionRegex = "(?s).*java(\\.[a-z]+)+\\.[A-Z][a-zA-Z]*Exception.*"; // (?s) = DOTALL mode
        return s.matches(exceptionRegex) || s.contains("Error: ") || s.contains("Failed: ");
    }
    
    SbazConnector() {
        setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        setEditable(false);
        setBackground(Color.black);
        setForeground(Color.white);
        processBuilder.redirectErrorStream();
    }

    Map<String, String> sbazInstalled() {
        Map<String, String> res = new HashMap<String, String>();
        for (String line: sbaz("installed").split("\n")) {
            if (!line.contains("/"))
                continue;
            String parts[] = line.split("/");
            res.put(parts[0].trim(), parts[1].trim());
        }
        return res;
    }

    List<String[]> sbazAvailable() {
        ArrayList<String[]> res = new ArrayList<String[]>();
        for (String line: sbaz("available", "-a").split("\n")) {
            if (!line.contains("("))
                continue;
            String parts[] = line.trim().split(" ");
            parts[1] = parts[1].substring(1, parts[1].length() - 1);
            for (int i = 2; i < parts.length; ++i)
                parts[i] = parts[i].substring(0, parts[i].length() - 1);
            res.add(parts);
        }
        return res;
    }

    String[] showInfo(String pv) {
        String[] res = new String[]{" ", " ", " ", " ", " ", " "};
        String out = sbaz("show", pv);
        if (!hasError(out)) {
            for (Pattern p: regexes) {
                Matcher m = p.matcher(out);
                if (m.matches()) {
                    res[0] = m.group(1);
                    res[1] = m.group(2);
                    res[2] = m.group(3);
                    res[3] = m.group(4);
                    if (m.groupCount() > 5) {
                        String name = m.group(5);
                        String value = m.group(6);
                        res[name.startsWith("Files") ? 4 : 5] = value;
                        if (m.groupCount() > 7) {
                            name = m.group(7);
                            value = m.group(8);
                            res[name.startsWith("Files") ? 4 : 5] = value;
                        }
                    } 
                    break;
                }
            }
        }
        return res;
    }

    private void handleChars(boolean app) {
        String lastLine = sbazOutBuilder.substring(bufLen);
        bufLen = sbazOutBuilder.length();
        if (app)
            append(lastLine);
        else
            Main.object.setMessage(lastLine.trim());
    }

    private void outputCommand() {
        commandLine.setLength(0);
        for (String c: sbazArgs) {
            commandLine.append(c).append(" ");
        }
        Main.object.setMessage(commandLine.toString());
    }

    synchronized String sbaz(String... args) {
        if (isWindows) {
            //sbazArgs.add("cmd"); sbazArgs.add("/c"); sbazArgs.add("sbaz");
            sbazArgs.add("sbaz.bat");
            if (Main.object.managedDirectory != null) {
                sbazArgs.add("-d");
                sbazArgs.add(String.format("\"%s\"", Main.object.managedDirectory));
            }
            for (String a: args) {
                if (a.matches("[a-zA-Z0-9]+"))
                    sbazArgs.add(a);
                else
                    sbazArgs.add(String.format("\"%s\"", a));
            }
        } else { // Unix variant
            sbazArgs.add("sbaz");
            if (Main.object.managedDirectory != null) {
                sbazArgs.add("-d");
                sbazArgs.add(Main.object.managedDirectory);
            }
            for (String a: args) {
                sbazArgs.add(a);
            }
        }
        append("> ");
        for (String a: sbazArgs) {
            append(a); append(" ");
        }
        append("\n");
        outputCommand();
        try {
            processBuilder.command(sbazArgs);
            Process process = processBuilder.start();
            InputStream is = process.getInputStream();
            int ch;
            bufLen = 0;
            while ((ch = is.read()) != -1) {
                if (ch == '\b') {
                    sbazOutBuilder.append('\n');
                    handleChars(false);
                    while (ch == '\b')
                        ch = is.read();
                }
                sbazOutBuilder.append((char)ch);
                if (ch == '\n')
                    handleChars(true);
            }
            if (bufLen != sbazOutBuilder.length())
                handleChars(true);
            process.waitFor();
            Main.object.setMessage("");
        } catch (Exception e) {
            String err = String.format("%s(%s)\n", e.getClass().getName(), e.getMessage());
            sbazOutBuilder.append(err);
            handleChars(true);
//            JOptionPane.showMessageDialog(this, err, "Spawn error", JOptionPane.ERROR_MESSAGE);
//            e.printStackTrace();
        }
        sbazArgs.clear();
        String res = sbazOutBuilder.toString();
        //append(res);
        append("\n");
        sbazOutBuilder.setLength(0);
        String hostErrorPattern = "java.net.UnknownHostException: ";
        String socketErrorPattern = "java.net.SocketException: ";
        String routeErrorPattern = "java.net.NoRouteToHostException: ";
        String pathErrorPattern = "java.io.IOException(Cannot run program \"sbaz";
        if (res.indexOf(hostErrorPattern) != -1 || res.indexOf(socketErrorPattern) != -1 || res.indexOf(routeErrorPattern) != -1) {
            int idx = res.indexOf("java.net.") + "java.net.".length();
            String errName = res.substring(idx, res.indexOf(" ", idx));
            JOptionPane.showMessageDialog(this, "<html><font color=\"red\">" +
                    String.format("A network error (%s) has occurred.", errName) +
                    "<br/>Please check the computer's network connection.</font><br/>" +
                    "<br/>Status (available, installed packages) will be reported correctly," +
                    "<br/>but install, upgrade, directory, and universe actions will fail.</html>",
                    "Network error", JOptionPane.ERROR_MESSAGE, null);
        } else if (res.indexOf(pathErrorPattern) != -1) {
            JOptionPane.showMessageDialog(this, "<html><font color=\"red\">Unable to run 'sbaz'. The Scala 'bin' directory <br/>" +
                    "must be added to the 'PATH' environment variable.</font></html>",
                    "Critical error: program will terminate", JOptionPane.ERROR_MESSAGE, null);
            System.exit(1);
        } else if (hasError(res)) {
            JOptionPane.showMessageDialog(this, "Check sbaz console for details", "Sbaz error", JOptionPane.ERROR_MESSAGE, null);
        }
        return res;
    }
    private ProcessBuilder processBuilder = new ProcessBuilder();
    private String osName = System.getProperty("os.name");
    private boolean isWindows = osName.contains("Windows");
    private StringBuilder sbazOutBuilder = new StringBuilder(), commandLine = new StringBuilder();
    private ArrayList<String> sbazArgs = new ArrayList<String>();
    private int bufLen = 0;
    private Pattern re1 = Pattern.compile("(?s)^Name:[ ]*([^\n]*)\n+Version:[ ]*([^\n]*)\n+Depends:[ ]*([^\n]*)\n+Description:\n+(.*)\n+(Link):[ ]*(.*)\n*$");
    private Pattern re2 = Pattern.compile("(?s)^Name:[ ]*([^\n]*)\n+Version:[ ]*([^\n]*)\n+Depends:[ ]*([^\n]*)\n+Description:\n+(.*)\n+(Files included):(.*)\n*$");
    private Pattern re3 = Pattern.compile("(?s)^Name:[ ]*([^\n]*)\n+Version:[ ]*([^\n]*)\n+Depends:[ ]*([^\n]*)\n+Description:\n+(.*)\n+(Files included):(.*)\n+(Link):[ ]*(.*)\n*$");
    private Pattern re4 = Pattern.compile("(?s)^Name:[ ]*([^\n]*)\n+Version:[ ]*([^\n]*)\n+Depends:[ ]*([^\n]*)\n+Description:\n+(.*)\n+(Link):[ ]*(.*)\n+(Files included):(.*)\n*$");
    //private Pattern re5 = Pattern.compile("(?s)Name:[ ]*([^\n]*)\n+Version:[ ]*([^\n]*)\n+Depends:[ ]*([^\n]*)\n+Description:\n+(.*)\n*");
    private Pattern[] regexes = new Pattern[] {re4, re3, re2, re1};
}
